//
//  MyInformationVC.m
//  wanzhaoIM
//
//  Created by liuyuantao on 15/5/7.
//  Copyright (c) 2015年 liuyuantao. All rights reserved.
//

#import "MyInformationVC.h"
#import "MicroDef.h"
#import "SettingNormalCell.h"
#import "SettingUserInfoCell.h"
#import "ModifyTelephoneVC.h"
#import "ModifyAddressVC.h"
#import "UIActionSheet+Blocks.h"
#import "RIButtonItem.h"
#import "CContactMgr.h"
//#import "CAccountMgr.h"
//#import "CAccountModel.h"
//#import "CDepartmentMgr.h"
//#import "CDepartmentModel.h"
#import "SDWebImageManager.h"
#import "UIImageView+WebCache.h"
#import "CXmppRequestMgr.h"
#import "AFNetworking.h"
#import "CDepartmentModel.h"
#import "CDepartmentMgr.h"
#import "MBProgressHUD+WZ.h"
#import "CFolderMgr.h"
#import "CServerSettingModel.h"
#import "FxImageCropViewController.h"
#import "CCompany.h"
#import "CCompanyMgr.h"
/*
 我的资料页
 可以添加、修改邮箱 地址 手机 电话。
 */

#define KSECTIONHEIGHT 20.0f
#define KHEADERCELLHEIGHT 75.0f
#define KNORMALCELLHEIGHT 60.0f
@interface MyInformationVC ()<UITableViewDelegate, UITableViewDataSource, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UIActionSheetDelegate,FxImageCropViewControllerDelegate, ModifyBaseControllerDelegate>
{
    UITableView *_tableView;
    UIScrollView *_scrollView;
    NSData *imageData;
}

@property (nonatomic, weak) UILabel *nameLabel;
@property (nonatomic, weak) UIButton *jobAndSexButton;
@property (nonatomic, weak) UIView *headerView;
@property (nonatomic, weak) UILabel *jobLabel;
@property (nonatomic, weak) UILabel *AutographLabel;

@end
@implementation MyInformationVC

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
     self.curuser = [[[CContactMgr alloc] init] loadCurContact];
    CContactMgr *contactMgr = [[CContactMgr alloc] init];
    CCompany *company = [[[CCompanyMgr alloc] init] loadCompanyWithcompCode:self.curuser.compCode];
    self.curuser.companyTelePhone = company.callcenterTelephone;
    [contactMgr updateContact:self.curuser];
    
    
    [self.navigationItem setHidesBackButton:YES];
    [self.navigationItem setNewTitleCenter:@"我的资料"];
    
    NSArray *list=self.navigationController.navigationBar.subviews;
    for (UIView *sub in list) {
        for (UIView *sub1 in sub.subviews) {
            
            if (sub1.height < 1.0f) {
                sub1.hidden = YES;
            }
        }
    }

    
     _scrollView = [[UIScrollView alloc] init];
    [_scrollView setBackgroundColor:[UIColor clearColor]];
    _scrollView.showsVerticalScrollIndicator = NO;
    _scrollView.scrollEnabled = YES;
    [self.view addSubview:_scrollView];
    
    UIView *scrollHeaderView = [[UIView alloc] init];
    scrollHeaderView.frame = CGRectMake(0, - HARDWARE_SCREEN_HEIGHT, HARDWARE_SCREEN_WIDTH, HARDWARE_SCREEN_HEIGHT);
    scrollHeaderView.backgroundColor = RGBCOLOR(0x2c, 0xaa, 0xfe);
    [_scrollView addSubview:scrollHeaderView];

    
//    UIView *superView = _scrollView;
    _tableView = [[UITableView alloc] init];
    _tableView.frame = self.view.frame;
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.showsHorizontalScrollIndicator = NO;
    _tableView.showsVerticalScrollIndicator = NO;
    _tableView.scrollEnabled = NO;
    [_scrollView addSubview:_tableView];
    _tableView.backgroundColor = [UIColor clearColor];
    
    UIView *headerView = [[UIView alloc] init];
    [headerView setBackgroundColor:RGBCOLOR(0x2c, 0xaa, 0xfe)];
    [_scrollView addSubview:headerView];
    self.headerView = headerView;
    
    UIImageView *headerImageView = [[UIImageView alloc] init];
    [headerImageView sd_setImageWithURL:[NSURL URLWithString:[[CXmppRequestMgr shareInstance] DownHeadFileWithContact:self.curuser.UserID]] placeholderImage:[UIImage imageNamed:@"testHeader"]];
    headerImageView.layer.cornerRadius = 10.0f/2;
    headerImageView.layer.masksToBounds = YES;
    [headerView addSubview:headerImageView];
    headerImageView.userInteractionEnabled=YES;
    UITapGestureRecognizer *singleTap =[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(onClickImage)];
    [headerImageView addGestureRecognizer:singleTap];
    self.headerImageView = headerImageView;
    
//    UIImageView *sexImageView;
//    if ([self.curuser.SEX isEqualToString:@"女"]) {
//        sexImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"womanIcon"]];
//    } else {
//    
//        sexImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"manIcon"]];
//    }
//    [headerView addSubview:sexImageView];
//    
//    UILabel *nameLabel = [[UILabel alloc] init];
//    nameLabel.text = self.curuser.UserName;
//    [nameLabel setTextAlignment:NSTextAlignmentLeft];
//    [nameLabel setTextColor:[UIColor whiteColor]];
//    [nameLabel setFont:[UIFont systemFontOfSize:14.0f]];
//    [headerView addSubview:nameLabel];
//    self.nameLabel = nameLabel;
    UIButton *nameAndSex = [[UIButton alloc] init];
    //    job.text = self.member.Position;
    nameAndSex.titleEdgeInsets = UIEdgeInsetsMake(0, 8.0, 0, 0);
    [nameAndSex setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    nameAndSex.userInteractionEnabled = NO;
    nameAndSex.titleLabel.font = Font18;
    [headerView addSubview:nameAndSex];
    if ([self.curuser.SEX isEqualToString:@"女"]) {
        
        [nameAndSex  setImage:[UIImage imageNamed:@"womanIcon"] forState:UIControlStateNormal];
    } else {
        [nameAndSex  setImage:[UIImage imageNamed:@"manIcon"] forState:UIControlStateNormal];
    }
    [nameAndSex setTitle:self.curuser.UserName forState:UIControlStateNormal];
    self.jobAndSexButton = nameAndSex;
    
    
    UILabel *AutographLabel = [[UILabel alloc] init];
    AutographLabel.text = self.curuser.Autograph;
    if (self.curuser.Autograph == nil || self.curuser.Autograph.length == 0) {
        AutographLabel.text = @"还未设置个人签名";
    }
    [AutographLabel setTextAlignment:NSTextAlignmentCenter];
    [AutographLabel setTextColor:[UIColor whiteColor]];
    [AutographLabel setFont:Font15];
    [headerView addSubview:AutographLabel];
    self.AutographLabel = AutographLabel;
    
    UILabel *job = [[UILabel alloc] init];
    job.text = self.curuser.Position;
    [job setTextAlignment:NSTextAlignmentCenter];
    [job setTextColor:[UIColor whiteColor]];
    [job setFont:Font15];
    [headerView addSubview:job];
    self.jobLabel = job;
       self.view.backgroundColor = RGBCOLOR(0xf3, 0xf3, 0xf3);
    
}

//从相册选择图片时，系统会默认将statubar设置成黑色，拍照选择照片时，系统会默认将statusbar隐藏，在以下两个方法中分别作处理可以解决问题
- (void)navigationController:(UINavigationController *)navigationController
      willShowViewController:(UIViewController *)viewController
                    animated:(BOOL)animated {
    
    if ([navigationController isKindOfClass:[UIImagePickerController class]] &&
        ((UIImagePickerController *)navigationController).sourceType == UIImagePickerControllerSourceTypePhotoLibrary) {
        [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:NO];
    }
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO];
    [[UIApplication sharedApplication] setStatusBarHidden:NO];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:NO];

    
    _scrollView.frame = self.view.bounds;
    self.headerView.frame = CGRectMake(0, 0, self.view.frame.size.width, 295.0f-64.0f);
    self.headerImageView.frame = CGRectMake((self.view.frame.size.width - 100) / 2.0f , 16.0f, 100, 100);
    self.jobAndSexButton.frame = CGRectMake((self.view.frame.size.width - 300) / 2.0f,  CGRectGetMaxY(self.headerImageView.frame) + 15.0f, 300, 30);
    self.jobLabel.frame = CGRectMake((self.view.frame.size.width - 300) / 2.0f ,454/2-64.0f, 300, 30);
    self.AutographLabel.frame = CGRectMake((self.view.frame.size.width - 300) / 2.0f, 514/2.0f-64.0f, 300, 30);
    _tableView.frame = CGRectMake(0, CGRectGetMaxY(self.headerView.frame), self.view.frame.size.width, 275.0f);

    
    [self modifyInfo];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{

//    if (scrollView.contentOffset.y > 0) {
//        _scrollView.backgroundColor = ClearColor;
//    } else {
//        _scrollView.backgroundColor = RGBCOLOR(0x2c, 0xaa, 0xfe);
//    }
}
- (void)scrollViewDidScrollToTop:(UIScrollView *)scrollView
{
    
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
//    NSLog(@"%@",NSStringFromCGRect(_tableView.frame));
    _scrollView.contentSize = CGSizeMake(HARDWARE_SCREEN_WIDTH, CGRectGetMaxY(_tableView.frame));

}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/


#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    NSInteger rows = 0;
    
    switch (section) {
        case 0:
            rows = 4;
            break;
        case 1:
            rows = 1;
            break;
        default:
            rows = 0;
            break;
    }
    return rows;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView              // Default is 1 if not implemented
{
    return 2;
}
// Row display. Implementers should *always* try to reuse cells by setting each cell's reuseIdentifier and querying for available reusable cells with dequeueReusableCellWithIdentifier:
// Cell gets various attributes set automatically based on table (separators) and data source (accessory views, editing controls)

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *NormalCellIdentifier = @"SettingNormalCell";
    
    UITableViewCell *cell = nil;
    
    SettingNormalCell *normalCell = [tableView dequeueReusableCellWithIdentifier:NormalCellIdentifier];
    if (normalCell == nil) {
        normalCell = [[[NSBundle mainBundle] loadNibNamed:@"SettingNormalCell" owner:self options:nil] objectAtIndex:0];
    }
    
    [normalCell.icon setImage:[UIImage imageNamed:[self iconName:indexPath]] forState:UIControlStateNormal];
    [normalCell.titleLabel setText:[self titleName:indexPath]];
    if((indexPath.section == 1 && indexPath.row == 0)
       || (indexPath.section == 0 && indexPath.row == 3) )
    {
        [normalCell.seperatorLine setHidden:YES];
    }
    else
    {
        [normalCell.seperatorLine setHidden:NO];
    }
    
    if((indexPath.section == 0 && indexPath.row == 0 )|| (indexPath.section == 0 && indexPath.row == 3))
    {
        [normalCell.rightArrow setHidden:YES];
        normalCell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    
    
    cell.accessoryType = UITableViewCellAccessoryNone;
    cell = normalCell;

    return cell;
}

-(NSString *)titleName:(NSIndexPath *)indexPath
{
    NSString *title = nil;
    
    switch (indexPath.section) {
        case 0:
        {
            switch (indexPath.row) {
                case 0:
                    if (self.curuser.companyTelePhone.length <= 0 ) {
                        title = self.curuser.EXtenSion;
                    } else {
                        
                        if (self.curuser.EXtenSion.length > 0) {
                            title = [NSString stringWithFormat:@"%@-%@",self.curuser.companyTelePhone,self.curuser.EXtenSion];
                        } else {
                            title = self.curuser.companyTelePhone;
                        }
                         
                    }

                    break;
                case 1:
                    title = self.curuser.MobileTelephone;
                    break;
                case 2:
                    title = self.curuser.Email;
                    break;
                case 3:
                    title = [[[CDepartmentMgr alloc] init] loadDepartment:self.curuser.DEPTID].DepartName;
                default:
                    break;
            }
        }
            break;
        case 1:
        {
            title = self.curuser.address;
        }
            break;
        default:
            break;
    }
    return title;
}

-(NSString *)iconName:(NSIndexPath *)indexPath
{
    NSString *iconName = nil;
    
    switch (indexPath.section) {
        case 0:
        {
            switch (indexPath.row) {
                case 0:
                    iconName = @"telephoneIcon";
                    break;
                case 1:
                    iconName = @"mobileTelephoneIcon";
                    break;
                case 2:
                    iconName = @"emailIcon";
                    break;
                case 3:
                    iconName = @"icon-zuzhijiagou";
                    break;
                default:
                    break;
            }
        }
            break;
        case 1:
        {
            iconName = @"addressIcon";
        }
            break;
        default:
            break;
    }
    return iconName;
}



#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    
    CGFloat height = 0;
    switch (section) {
        case 1:
            height = KSECTIONHEIGHT;
            break;
        default:
            break;
    }
    return height;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    CGFloat height = 0;
    switch (section) {
        case 1:
            height = 2;
            break;
        default:
            break;
    }
    return height;
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section   // custom view for header. will be adjusted to default or specified header height
{
    UIView *headerView = nil;
    if(section == 0)
    {
        return headerView;
    }
    headerView = [[UIView alloc] init];
    headerView.frame = CGRectMake(0, 0, tableView.frame.size.width, KSECTIONHEIGHT);
    headerView.backgroundColor = RGBCOLOR(0xf3, 0xf3, 0xf3);
    UIView *beginLine = [[UIView alloc] init];
    beginLine.frame = CGRectMake(0, 0, tableView.frame.size.width, 0.5);
    [beginLine setBackgroundColor:KSEPERATORLINECOLOR];
    [headerView addSubview:beginLine];
    
    UIView *endLine = [[UIView alloc] init];
    endLine.frame = CGRectMake(0, KSECTIONHEIGHT-0.5, tableView.frame.size.width, 0.5);
    [endLine setBackgroundColor:KSEPERATORLINECOLOR];
    [headerView addSubview:endLine];
    
    return headerView;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section   // custom view for footer. will be adjusted to default or specified footer height
{
    UIView *headerView = nil;
    if(section != 1)
    {
        return headerView;
    }
    headerView = [[UIView alloc] init];
    headerView.frame = CGRectMake(0, 0, tableView.frame.size.width, 2);
    headerView.backgroundColor = RGBCOLOR(0xf3, 0xf3, 0xf3);
    UIView *beginLine = [[UIView alloc] init];
    beginLine.frame = CGRectMake(0, 0, tableView.frame.size.width, 0.5);
    [beginLine setBackgroundColor:KSEPERATORLINECOLOR];
    [headerView addSubview:beginLine];
    return headerView;
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat height = 50.0f;
    
    if(indexPath.row == 0 && indexPath.section == 0)
    {
        height = 50.0f;
    }
    return height;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    self.indexPath = indexPath;
    NSString *title;
    switch (indexPath.section) {
        case 0:
        {
            switch (indexPath.row) {
                case 0:
                {
//                    [self showModifyTelVC];
                    title = @"修改分机号";
                }
                    break;
                case 1:
                {
                    title = @"修改手机号码";
                    UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:title, nil];
                    [sheet showInView:self.view];

//                    [self showMobileTelVC];
                }
                    break;
                case 2:
                {
                    title = @"修改邮箱地址";
                    UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:title, nil];
                    [sheet showInView:self.view];

//                    [self showModifyEmailVC];
                }
                    break;
                default:
                    break;
            }
        }
            break;
        case 1:
        {
            title = @"修改地址";
            UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:title, nil];
            [sheet showInView:self.view];

//            [self showModifyAddressVC];
        }
            break;
        default:
            break;
    }
    
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    switch (buttonIndex) {
        case 0:
        {
            switch (self.indexPath.section) {
                case 0:
                {
                    switch (self.indexPath.row) {
                        case 0:
                        {
                            //                    [self showModifyTelVC];
                        }
                            break;
                        case 1:
                        {
                            [self showMobileTelVC];
                        }
                            break;
                        case 2:
                        {
                            [self showModifyEmailVC];
                        }
                            break;
                        default:
                            break;
                    }
                }
                    break;
                case 1:
                {
                    [self showModifyAddressVC];
                }
                    break;
                default:
                    break;
            }

        }
            break;
        case 1:
        {
                    }
            break;
        default:
            break;
    }
}
-(void)showModifyTelVC
{
//    ModifyTelephoneVC
    ModifyTelephoneVC *modifyTel = [[ModifyTelephoneVC alloc] init];
   

//    CHSNavigationController *modifyTelNav = [[CHSNavigationController alloc] initWithRootViewController:modifyTel];
    modifyTel.vc_type = @"0";
    modifyTel.curUser = self.curuser;
    modifyTel.delegate = self;
    [self.navigationController pushViewController:modifyTel animated:YES];
    //    [self.leveyTabBarController setHidesBottomBarWhenPushed:YES];
}

-(void)showMobileTelVC
{
    
    ModifyTelephoneVC *modifyTel = [[ModifyTelephoneVC alloc] init];
        modifyTel.vc_type = @"1";
    modifyTel.curUser = self.curuser;
    modifyTel.delegate = self;
//    CHSNavigationController *modifyTelNav = [[CHSNavigationController alloc] initWithRootViewController:modifyTel];
    [self.navigationController pushViewController:modifyTel animated:YES];
}

-(void)showModifyEmailVC
{
    

    ModifyTelephoneVC *modifyTel = [[ModifyTelephoneVC alloc] init];
   
    modifyTel.vc_type = @"2";
    modifyTel.delegate = self;
    modifyTel.curUser = self.curuser;
//    CHSNavigationController *modifyTelNav = [[CHSNavigationController alloc] initWithRootViewController:modifyTel];
    [self.navigationController pushViewController:modifyTel animated:YES];
}

-(void)showModifyAddressVC
{
   
    ModifyAddressVC *modifyAddr = [[ModifyAddressVC alloc] init];
    modifyAddr.curUser = self.curuser;
    modifyAddr.delegate = self;
//    CHSNavigationController *modifyAddrNav = [[CHSNavigationController alloc] initWithRootViewController:modifyAddr];
    [self.navigationController pushViewController:modifyAddr animated:YES];
}

#pragma mark ModifyBaseControllerDelegate
- (void)modifyInfo
{
    
    [[[CContactMgr alloc] init] updateContact:self.curuser];
    
    
    [_tableView reloadData];
}


-(void)onClickImage
{
    
//    NSLog(@"图片被点击!");
    RIButtonItem *cancelItem = [RIButtonItem itemWithLabel:@"取消" action:^{

    }];
    
    __block MyInformationVC *block = self;
    RIButtonItem *photoItem = [RIButtonItem itemWithLabel:@"拍照" action:^{
        UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
        [imagePickerController setDelegate:block];
        if ([UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceFront]) {
            [imagePickerController setSourceType:UIImagePickerControllerSourceTypeCamera];
        }
        else
        {
            [imagePickerController setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
        }
//        [imagePickerController setAllowsEditing:YES];
        [block presentViewController:imagePickerController animated:YES completion:nil];
    }];
    
    RIButtonItem *selectItem = [RIButtonItem itemWithLabel:@"从相册选择" action:^{
        UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
        [imagePickerController setDelegate:block];
        [imagePickerController setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
//        [imagePickerController setAllowsEditing:YES];
        [block presentViewController:imagePickerController animated:YES completion:NULL];
    }];
    
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:nil cancelButtonItem:cancelItem destructiveButtonItem:selectItem otherButtonItems:photoItem, nil];
    [actionSheet showInView:self.view];
}



#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
//    bug
    UIImage *photo = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
    FxImageCropViewController *imageCropVC = [[FxImageCropViewController alloc] initWithImage:photo cropMode:RSKImageCropModeSquare];
    
    imageCropVC.delegate = self;
    [picker pushViewController:imageCropVC animated:YES];
 
    
}


//-(void)UploadHeadFileWithImageData:(UIImage *)image userId:(NSString *)userId
//{
//    NSData *imageData = UIImageJPEGRepresentation(image, 0.4);
//    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
//    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
//    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
//    [manager setTaskDidSendBodyDataBlock:^(NSURLSession *session, NSURLSessionTask *task, int64_t bytesSent, int64_t totalBytesSent, int64_t totalBytesExpectedToSend) {
//        NSLog(@"bytesSent:%lld, totalBytesSent:%lld, totalBytesExpectedToSend:%lld", bytesSent, totalBytesSent, totalBytesExpectedToSend);
//    }];
//    
//    [manager POST:[[CXmppRequestMgr shareInstance] UploadHeadFileWithUserId:userId]  parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
//        [formData appendPartWithFileData:imageData name:@"testHeader.png" fileName:@"testHeader.png" mimeType:@"img/png"];
//    } success:^(NSURLSessionDataTask *task, id responseObject) {
//        
//        NSLog(@"%@",responseObject);
//        [[SDWebImageManager sharedManager].imageCache removeImageForKey:[[CXmppRequestMgr shareInstance] DownHeadFileWithContact:userId]];
//        [[SDWebImageManager sharedManager].imageCache removeImageForKey:[[CXmppRequestMgr shareInstance] DownHeadFileWithContact:userId] fromDisk:YES];
//
//        [[SDWebImageManager sharedManager] saveImageToCache:image forURL:[NSURL URLWithString:[[CXmppRequestMgr shareInstance] DownHeadFileWithContact:userId]]];
////         NSString *str = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
////        NSLog(@"str:%@", str);
////        NSLog(@"Success %@", responseObject);
//
////        [self.headerImageView setImage:image];
//        [self.headerImageView sd_setImageWithURL:[NSURL URLWithString:[[CXmppRequestMgr shareInstance] DownHeadFileWithContact:self.curuser.UserID]] placeholderImage:[UIImage imageNamed:@"testHeader"]];
//        
//    } failure:^(NSURLSessionDataTask *task, NSError *error) {
//        NSLog(@"hhahaahah");
//        NSLog(@"%@",error.localizedDescription);
//    }];
//    
//}


- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:^(){
    }];
}

- (void)imageCropViewControllerDidCancelCrop:(FxImageCropViewController *)controller
{
    imageData = nil;
    
    [controller dismissViewControllerAnimated:YES completion:nil];
}

- (void)imageCropViewController:(FxImageCropViewController *)controller didCropImage:(UIImage *)croppedImage
{
    UIImage *image = croppedImage;
    image = [self scaleToSize:image size:CGSizeMake(170, 170)];
     imageData = UIImageJPEGRepresentation(image, 0.4);
    
    [[CXmppRequestMgr shareInstance] UploadHeadFileWithImageData:imageData userId:self.curuser.UserID userCode:self.curuser.UserCode successHandel:^(NSURLSessionDataTask *task, id responseObject) {
        
        
        [[SDWebImageManager sharedManager].imageCache storeImage:image forKey:[[CXmppRequestMgr shareInstance] DownHeadFileWithContact:self.curuser.UserID]];
        [[SDWebImageManager sharedManager].imageCache storeImage:image forKey:[[CXmppRequestMgr shareInstance] DownHeadFileWithContact:self.curuser.UserID] toDisk:YES];
        //        NSString *str = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        //        NSLog(@"str:%@", str);
        //        NSLog(@"Success %@", responseObject);
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.headerImageView sd_setImageWithURL:[NSURL URLWithString:[[CXmppRequestMgr shareInstance] DownHeadFileWithContact:self.curuser.UserID]] placeholderImage:[UIImage imageNamed:@"testHeader"]];
        });
        
        
    } filarueHandle:^(NSURLSessionDataTask *task, NSError *error) {
        
        [MBProgressHUD showError:@"网络错误，保存失败！"];
        
    } progressHandle:^(NSURLSession *session, NSURLSessionTask *task, int64_t bytesSent, int64_t totalBytesSent, int64_t totalBytesExpectedToSend) {
        
    }];
    
   [self dismissViewControllerAnimated:YES completion:nil];
}





- (UIImage *)scaleToSize:(UIImage *)img size:(CGSize)size{
    // 创建一个bitmap的context
    // 并把它设置成为当前正在使用的context
    UIGraphicsBeginImageContext(size);
    // 绘制改变大小的图片
    [img drawInRect:CGRectMake(0, 0, size.width, size.height)];
    // 从当前context中创建一个改变大小后的图片
    UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    // 使当前的context出堆栈
    UIGraphicsEndImageContext();
    // 返回新的改变大小后的图片
    return scaledImage;
}
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    cell.transform =  CGAffineTransformMakeTranslation(HARDWARE_SCREEN_WIDTH, 0);
    [UIView animateWithDuration:1 delay:0 usingSpringWithDamping:0.6 initialSpringVelocity:0 options:0 animations:^{
        cell.transform = CGAffineTransformIdentity;
    } completion:NULL];
}

@end
